package com.xixudi.htmlto;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc jfinal-weixin wiki doc 爬取并生成chm
 * @author YangZheng 328170112@qq.com
 * @date 2019-02-20 22:16
 */
public class JifinalWeixinDoc {
    private static final Logger log = LoggerFactory.getLogger(JifinalWeixinDoc.class);

    private static String projectName="jfinal-weixin";
    private static String basePath= JifinalWeixinDoc.class.getClassLoader().getResource("").getPath()+projectName;
    private static Template template = Engine.use().setBaseTemplatePath(basePath).getTemplate("template.html");
    private static Map<String,String> cookie = new HashMap<String,String>(){{
        //突然发现换成Host也行,遂换之
//        put("X-CSRF-Token","");
        put("X-Requested-With","XMLHttpRequest");
        put("Host","gitee.com");
    }};
    public static String getPageHtml(String url){
        try {
            log.info("url:{}",url);
            Connection conn = Jsoup.connect(url).ignoreContentType(true).headers(cookie);
            String body = conn.execute().body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            Integer code = jsonObject.getInteger("code");
            String html="",title;
            if(code.equals(200)) {
                log.info("jsonObject:{}",jsonObject);
                JSONObject wiki = jsonObject.getJSONObject("wiki");
                title = wiki.getString("title");
                String contentHtml = wiki.getString("content_html");
                html = contentHtml.replace("\\n", "").replace("\\'", "\"").replace("\\/", "/").replace("\\\"", "\"");
            } else {
                log.error("jsonObject:{}",jsonObject);
                title = URLDecoder.decode(url.substring(url.lastIndexOf("=")+1), "utf8");
                if(code.equals(404)) {
                    html = "<h2>404</h2><p><a href=\"https://gitee.com/jfinal/jfinal-weixin/wikis"+url.substring(url.lastIndexOf("/"))+"\">"+ title +"</a></p>";
                }
            }
            return template.renderToString(Kv.by("html", html).set("title", title));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void saveHtml(String html,String name){
        FileOutputStream out = null;
        try {
            out = (new FileOutputStream(new File(basePath + "/source/" + name)));
            out.write(html.getBytes("utf8"));
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(out==null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static ArrayList<ContentsNode> downResource(){
        ArrayList<ContentsNode> nodes = new ArrayList<>();
        String baseUrl = "https://gitee.com/jfinal/jfinal-weixin/wikis/pages/wiki?&parent=&version_id=master&info_id=20719&wiki_title=";
        try {
            String html = getPageHtml(baseUrl + "Home");
            Document doc1 = Jsoup.parse(html);
            Elements menus = doc1.select(".markdown-body>*:gt(2)");
            int h=0,t=0;
            for (Element menu : menus) {
                Elements a = menu.select("a");
                String href = a.attr("href");
                if(href.startsWith("http")) {
                    t++;
                    String indexStr = h+"-"+t;
                    nodes.add(ContentsNode.newTopic(h+"."+menu.text(), indexStr+".html"));
                    String substring = href.substring(href.lastIndexOf("/")+1);
                    saveHtml(getPageHtml(baseUrl +substring),indexStr+".html");
                } else {
                    h++;
                    t=0;
                    nodes.add(ContentsNode.newHeading(h+"."+menu.text()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nodes;
    }
    public static void main(String[] args) {
        ArrayList<ContentsNode> contentsDownNodes = downResource();
        String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
        MakeChm.createChm(projectName,contentsDownNodes,"index.html","jfinal-weixin帮助文档@"+today,true);
    }

}